package com.material.common.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author ganxinge
 */
public class JsonTypeHandler<T> implements TypeHandler<T> {
    private static final ObjectMapper objectMapper = new ObjectMapper();
    private Class<T> type;

    public JsonTypeHandler(Class<T> type) {
        if (type == null) {
            throw new IllegalArgumentException("Type argument cannot be null");
        }
        this.type = type;
    }

    @Override
    public void setParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
        try {
            ps.setString(i, parameter == null ? null : objectMapper.writeValueAsString(parameter));
        } catch (JsonProcessingException e) {
            throw new SQLException("Error converting object to JSON", e);
        }
    }

    @Override
    public T getResult(ResultSet rs, String columnName) throws SQLException {
        try {
            return rs.getString(columnName) == null ? null : objectMapper.readValue(rs.getString(columnName), type);
        } catch (Exception e) {
            throw new SQLException("Error converting JSON to object", e);
        }
    }

    @Override
    public T getResult(ResultSet rs, int columnIndex) throws SQLException {
        try {
            return rs.getString(columnIndex) == null ? null : objectMapper.readValue(rs.getString(columnIndex), type);
        } catch (Exception e) {
            throw new SQLException("Error converting JSON to object", e);
        }
    }

    @Override
    public T getResult(CallableStatement cs, int columnIndex) throws SQLException {
        try {
            return cs.getString(columnIndex) == null ? null : objectMapper.readValue(cs.getString(columnIndex), type);
        } catch (Exception e) {
            throw new SQLException("Error converting JSON to object", e);
        }
    }
}
